﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using QD.Utill;
using QD.Snapshot.Core.Config;
using NSoup.Nodes;
using System.Text.RegularExpressions;
using NSoup.Select;
using QD.Snapshot.Core.Util;

namespace QD.Snapshot.Core.BLL
{
    public class Search_Baidu : SearchBase
    {

        public Search_Baidu(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "0";        //百度搜索引擎
            Echo("百度截图已启动");
        }

        
        HttpRequest Http = new HttpRequest();
        string htmls, msg;
        Model.TaskModel taskModel = new Model.TaskModel();
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            Thread.Sleep(SleepTime);
            Http.UserAgent = "Mozilla/5.0 (compatible;Windows NT 6.1; WOW64;Trident/6.0;MSIE 9.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.27 Safari/537.36";

            if (string.IsNullOrEmpty(htmls))
                Http.Request_BD("https://www.baidu.com", out msg);
            for (int i = 1; i <= 3; i++)
            {
                htmls = string.Empty;
                Http.Referer = string.Format(Engine.URL_BD, StringHelper.ConvertUrl(keyword), (i - 1) * 10);
                msg = Http.Request_BD(string.Format(Engine.URL_BD, keyword, (i - 1) * 10), out htmls);

                IsCode_BD = CheckCode(htmls);   //是否出现验证码
                if (msg.Length > 0)
                {
                    Echo(string.Format("搜索 {0} 验证码", keyword));
                }
                else if (IsCode_BD)
                {
                    EchoCodeLog(EngineType.BaiDu, "百度出现验证码");
                    Thread.Sleep(1000);
                }
                else
                {
                    Echo(string.Format("搜索 {1}页 {0}", keyword, i));
                }

                taskModel.keyword = keyword;
                taskModel.product = product;
                taskModel.company = company;
                taskModel.html = htmls;
                taskModel.page = i;

                NumHelper.Instance.SetNumBD(1);    //统计搜索速度
                ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
            }
        }


        void CheckOrAdd(object obj)
        {
            var model = obj as Model.TaskModel;
            model.html = Regex.Replace(model.html, "<!--([\\s\\S].*?)-->", "");
            CheckOrAdd(model.html, model.keyword, model.product, model.company, model.page);
        }
        void CheckOrAdd(string html, string keyword, Model.Product product, Model.WebSite company, int page)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, keyword, product, page);
        }

        private readonly object obj = new object();
        Model.Snap snapModel = new Model.Snap();
        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, string keyword, Model.Product product, int page)
        {
            Element result = doc.GetElementById("content_left");
            if (result == null) return;

            HideElement(doc.GetElementById("content_right"));   //去掉右侧
            HideElementList(result.Select(".general_image_pic"));   //去掉每行左边的图片
            //去掉百度广告
            for (int i = 1; i <= 5; i++)
            {
                HideElement(doc.GetElementById(Convert.ToString(i + 3000)));
                HideElement(doc.GetElementById(Convert.ToString(i + 4000)));
                HideElement(doc.GetElementById(Convert.ToString(i + 5000)));
            }

            bool isFirst = true;
            string nums_html = "";

            for (int i = 1, j = 1; i <= 10; i++, j++)
            {
                j = i + ((page - 1) * 10);   //2014-01-21  百度第2页第3页
                Element ele = result.GetElementById(j.ToString());
                if (null == ele) continue;

                if (ele.Text().IndexOf("map_singlepoint") > -1 && ele.Text().IndexOf("map.baidu.com") > -1)   //去掉百度地图
                    HideElement(ele);

                //匹配成功条件：简称|| 简称列表|| 勤加缘网站
                //勤加缘规则：标题有公司简称或者含有电话号码手机号码和公司简称 或者标题含有关键词和含有公司简称
                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY_BD(ele.Text(), SiteName, Cellphone, phone, product))
                {
                    string index_key = GetMd5(ele.Text()); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Html());    //上词的平台

                    if (isFirst)
                    {
                        RemoveAttr(result); //删除链接
                        nums_html = "<span id='sp_nums' class='sp_nums' data='" + doc.Select(".nums").Text + "'></span>";
                        isFirst = false;
                    }

                    //添加成功记录
                    lock (obj)
                    {
                        snapModel.itemid = product.itemid;
                        snapModel.userid = product.userid;
                        snapModel.keyword = keyword;
                        snapModel.ranking = i;
                        snapModel.copyform = Convert.ToInt32(copyform);
                        snapModel.page = page;
                        snapModel.state = 0;
                        snapModel.clientid = SiteConfig.ClientId;
                        snapModel.platform = platform;
                        snapModel.updatetime = DateTime.Now;
                        snapModel.index_key = index_key;
                        snapModel.html = result.Html() + nums_html;
                        AddSnap(snapModel);
                        BLL.File.Snap.AddSnap(snapModel);
                    }
                }
            }
        }

        /// <summary>
        /// 勤加缘匹配 百度
        /// </summary>
        bool CheckQJY_BD(string html, Regex SiteName, Regex Cellphone, Regex phone, Model.Product product)
        {
            if (html.IndexOf("qjy168.com") == -1) return false;
            //公司全称、电话、手机匹配
            if (SiteName.IsMatch(html) || Cellphone.IsMatch(html) || phone.IsMatch(html))
                return true;
            return false;
        }




        void RemoveAttr(Element result)
        {
            result.RemoveAttr("c-container");

            Elements div = result.Select("div");
            div.RemoveAttr("c-container");
            div.RemoveAttr("srcid");
            div.RemoveAttr("tpl");
            div.RemoveAttr("data-click");
            div.RemoveAttr("data-tools");
            div.RemoveAttr("id");

            Elements a = result.Select("a");
            a.Attr("href", "#");
            a.RemoveAttr("data-click");
            a.RemoveAttr("target");

            Elements span = result.Select("span");
            span.RemoveAttr("data_key");
            span.RemoveAttr("hint-data");
            span.RemoveAttr("hint-type");

            Elements script = result.Select("script");
            script.Remove();

            //百度图片
            Elements bd_pic = result.Select(".result-op");
            bd_pic.Remove();
        }
    }
}